package com.jake.springboot.order.processor;

import com.google.common.collect.Maps;
import com.jake.springboot.order.annotation.OrderTypeAnnotation;
import com.jake.springboot.order.constant.OrderTypeEnum;
import com.jake.springboot.order.context.StrategyContext;
import com.jake.springboot.order.util.ClassScanner;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class StrategyProcessor implements BeanFactoryPostProcessor {

    private static final String STRATEGY_PACKAGE = "com.jake.springboot.order.strategy";

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        HashMap<OrderTypeEnum, Class<?>> handlerMap = Maps.newHashMapWithExpectedSize(3);
        ClassScanner.scan(STRATEGY_PACKAGE, OrderTypeAnnotation.class).forEach(clazz -> {
            OrderTypeEnum type = clazz.getAnnotation(OrderTypeAnnotation.class).orderType();
            handlerMap.put(type, clazz);
        });
        StrategyContext context = new StrategyContext(handlerMap);
        configurableListableBeanFactory.registerSingleton(StrategyContext.class.getName(), context);
    }

}
